package com.anolesoft.twelvePlan.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.twelvePlan.dto.*;
import com.anolesoft.twelvePlan.listener.MesEqualCatalogListener;
import com.anolesoft.twelvePlan.listener.PlanCheckListener;
import com.anolesoft.twelvePlan.service.PlanCheckService;
import com.anolesoft.twelvePlan.vo.*;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.PageData;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zyq
 * @date 2022/3/25
 */
@RestController
@RequestMapping(value="/check")
@Slf4j
public class PlanCheckController {
    @Autowired
    private PlanCheckService planCheckService;

    @PostMapping(value = "/selectJx")
    public AjaxResult selectJx(@RequestBody PlanCheckVO planCheckVO) {
        log.debug("planCheckVO：{}" + planCheckVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        planCheckVO.setFactoryId(loginUser.getFacCode());
        PlanCheckDTO planCheckDTO = BeanUtil.copyProperties(planCheckVO, PlanCheckDTO.class);
        log.debug("planCheckDTO: {}",planCheckDTO);
        List<MesPlanXiadaJixingDTO> mesPlanXiadaJixingDTOList = this.planCheckService.selectJx(planCheckDTO);
        List<MesPlanXiadaJixingVO> mesPlanXiadaJixingVOList = mesPlanXiadaJixingDTOList.stream()
                .map(t -> BeanUtil.copyProperties(t, MesPlanXiadaJixingVO.class))
                .collect(Collectors.toList());
        return AjaxResult.success("查询成功", mesPlanXiadaJixingVOList);
    }

    @PostMapping(value = "/queryCheck")
    public AjaxResult queryPlanInfo(@RequestBody PlanCheckVO planCheckVO){
        log.debug("planCheckVO：{}" + planCheckVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        planCheckVO.setFactoryId(loginUser.getFacCode());
        Integer pageSize = planCheckVO.getPageSize();
        Integer pageNo = planCheckVO.getPageNo();
        String waixieString = this.arrayToString(planCheckVO.getWaixies());
        String jxString = this.arrayToString(planCheckVO.getJxList());
        String plangrade = this.arrayToString(planCheckVO.getPlangrades());
        planCheckVO.setWaixie(waixieString);
        planCheckVO.setJx(jxString);
        planCheckVO.setPlangrade(plangrade);
        //log.debug("外协字符串：" + waixieString);
        PlanCheckDTO planCheckDTO = BeanUtil.copyProperties(planCheckVO, PlanCheckDTO.class);
        log.debug("planCheckDTO：{}" + planCheckDTO);
        PageData<List<PlanCheckDTO>> listPageData = this.planCheckService.queryCheck(planCheckDTO, pageNo, pageSize);
        List<PlanCheckVO> planCheckVOList = listPageData.getItems().stream()
                .map(t -> BeanUtil.copyProperties(t, PlanCheckVO.class))
                .collect(Collectors.toList());
        PageResult pageResult = new PageResult(planCheckVOList, pageSize, pageNo, listPageData.getTotal());
        return AjaxResult.success("查询成功", pageResult);
    }

    @PostMapping(value = "/updateCheck")
    public AjaxResult updateGyInfo(@RequestBody PlanCheckVO planCheckVO){
        log.debug("planCheckVO: {}",planCheckVO);
        PlanCheckDTO planCheckDTO = BeanUtil.copyProperties(planCheckVO, PlanCheckDTO.class);
        log.debug("planCheckDTO: {}",planCheckDTO);
        if (this.planCheckService.updateCheck(planCheckDTO) != 1) {
            return AjaxResult.success("修改失败，请重试");
        }
        return AjaxResult.success("修改成功！");
    }
    @PostMapping(value = "/checkPlan")
    public AjaxResult checkPlan(@RequestBody String[] objuids){
        for (String s: objuids) {
            System.out.println(s);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String checksUid = loginUser.getEmpUid();
        System.out.println(checksUid);
        if (this.planCheckService.checkPlan(objuids, checksUid) != objuids.length) {
            return AjaxResult.success("核对失败，请重试");
        }
        return AjaxResult.success("核对成功！");
    }

    @PostMapping(value = "/chargePerson")
    public AjaxResult chargePerson(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String factoryId = loginUser.getFacCode();
        List<StfEmployeeToChargeVO> stfEmployeeToChargeVOList = this.planCheckService.chargePerson(factoryId);
        return AjaxResult.success("查询成功", stfEmployeeToChargeVOList);
    }

    @PostMapping(value = "/planGrade")
    public AjaxResult planGrade(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String factoryId = loginUser.getFacCode();
        List<MesPlanGradeDTO> mesPlanGradeDTOS = this.planCheckService.planGrade(factoryId);
        List<MesPlanGradeVO> mesPlanGradeVOS = mesPlanGradeDTOS.stream()
                .map(t -> BeanUtil.copyProperties(t, MesPlanGradeVO.class))
                .collect(Collectors.toList());
        return AjaxResult.success("查询成功", mesPlanGradeVOS);
    }

    @PostMapping(value = "/blanking")
    @ResponseBody
    public AjaxResult selectBlanking(@RequestBody Map<String,String> map){
        log.debug("map: {}",map);
        String blanking = this.planCheckService.selectBlanking(map.get("objuid"));
        return AjaxResult.success(blanking);
    }

    @PostMapping(value = "/outsourcing")
    @ResponseBody
    public AjaxResult selectOutsourcing(@RequestBody Map<String,String> map){
        log.debug("map: {}",map);
        String outsourcing = this.planCheckService.selectOutsourcing(map.get("objuid"));
        return AjaxResult.success(outsourcing);
    }

    @PostMapping(value = "/mesProgress")
    public AjaxResult mesProgress(@RequestBody PlanCheckVO planCheckVO) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        planCheckVO.setFactoryId(loginUser.getFacCode());
        log.debug("制造记录查询:{}",planCheckVO);
        PlanCheckDTO planCheckDTO = BeanUtil.copyProperties(planCheckVO, PlanCheckDTO.class);
        List<MesOrderTraceTiaoMaVO> mes = this.planCheckService.mesProgress(planCheckDTO);
        return AjaxResult.success(mes);
    }

    @PostMapping(value="/export")
    public void queryMatchExport(@RequestBody PlanCheckVO planCheckVO, HttpServletResponse response){
        long start = System.currentTimeMillis();
        //OutputStream output = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        planCheckVO.setFactoryId(loginUser.getFacCode());
        String waixieString = this.arrayToString(planCheckVO.getWaixies());
        String jxString = this.arrayToString(planCheckVO.getJxList());
        String plangrade = this.arrayToString(planCheckVO.getPlangrades());
        planCheckVO.setWaixie(waixieString);
        planCheckVO.setJx(jxString);
        planCheckVO.setPlangrade(plangrade);
        //planCheckVO.setWaixie(waixieString.toString());
        //log.debug("外协字符串：" + waixieString.toString());
        log.debug("planCheckVO: {}", planCheckVO);
        PlanCheckDTO planCheckDTO = BeanUtil.copyProperties(planCheckVO, PlanCheckDTO.class);
        log.debug("planCheckDTO: {}", planCheckDTO);
        try {
            OutputStream output = response.getOutputStream();
            //字符集
            response.setCharacterEncoding("utf-8");
            //类型
            response.setContentType("multipart/form-data");
            //响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(("export.xlsx").getBytes("gb2312"),"ISO8859-1"));
            //总条数
            int total = this.planCheckService.exportCheck(planCheckDTO,1,10).getTotal();
            log.debug("total:" + total);
            //单个sheet最大条数
            int size = 100000;
            //sheet数
            int sheet = total / size + 1;
            //单次查询条数
            int pageSize = 1000;
            ExcelWriter excelWriter = EasyExcel.write(output).build();
            //执行查询次数
            int count = 1;
            for (int i = 0; i < sheet ; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i,"进度核对" + (i+1))
                        .head(PlanCheckExport.class)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .build();
                int rolling;
                if (i == sheet - 1) {
                    rolling = (total - i * size) / pageSize + 1;
                } else {
                    rolling = size / pageSize;
                }
                for (int j = 0; j < rolling; j++) {
                    PageData<List<PlanCheckExport>> exportCheck = this.planCheckService.exportCheck(planCheckDTO, count, pageSize);
                    List<PlanCheckExport> datas = exportCheck.getItems();
                    excelWriter.write(datas, writeSheet);
                    count++;
                }
            }
            log.debug("查询次数：" + (count - 1) + "次");
            //刷新流
            excelWriter.finish();
            output.flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("导出失败：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            long end = System.currentTimeMillis();
            log.debug("总用时：" + (end - start) + "毫秒");
        }
    }

    @PostMapping(value="/import")
    public AjaxResult importMatchExport(MultipartFile file){
        log.debug("文件名：{}", file.getOriginalFilename());
        log.debug("文件大小：{}", file.getSize());

        try {
            EasyExcel.read(file.getInputStream(), PlanCheckImport.class, new PlanCheckListener(planCheckService)).sheet(0).doRead();
            return AjaxResult.success("文件导入成功！");
        } catch (IOException e) {
            log.error("导入失败：{}", e.getMessage());
            e.printStackTrace();
            return AjaxResult.success("文件导入异常" + e.getMessage());
        }
    }

    /**
     * 下拉选多选数组转模糊查询字符串
     * @param array
     * @return
     */
    private String arrayToString(String[] array) {
        StringBuffer str = new StringBuffer();
        if (array != null && array.length > 0) {
            for (String s: array) {
                str.append("'");
                str.append(s);
                str.append("',");
            }
        }
        if (str.length() > 1) {
            str.setLength(str.length()-1);
        }
        log.debug("字符串数组转字符串结果：" + str.toString());
        return str.toString();
    }

}
